<?php
/**
 * Created by PhpStorm.
 * User: liuxiaojie
 * Date: 2019-05-11
 * Time: 20:47
 */

namespace app\crontab\controller;

use app\model\Customer;
use app\model\ServiceConfig;
use app\tools\Wx;
use think\Db;
use think\Exception;

class Index{

    // 范围内有订单；

    function order(){

        $orders = db('repair_order')->where(['is_tui' => 0, 'status'=> 20, 'sheet_type'=> 2])->field('id, type, lat, lng, order_no, add_time, details')->select();

        $shifu = db('repair_person p')
            ->join('customer c', 'c.id = p.customer_id')
            ->where(['p.status'=> ['in', [3, 5]]])
            ->field('p.lat, p.lng, p.service_type, p.distance, c.unionid')
            ->select();

//        dump($shifu);

        $wx = new Wx();

        foreach ($orders as $v)
        {
            foreach ($shifu as $vv)
            {
                $type_arr = explode(',', $vv['service_type']);
//                dump($type_arr);
//                echo $v['type'];
                if(in_array($v['type'], $type_arr))
                {
                    $juli = getDistance($vv['lng'], $vv['lat'], $v['lng'], $v['lat'], 1);
                    if($juli <= $vv['distance'])
                    {
                        $openid = db('customer')->where(['unionid'=> $vv['unionid'], 'type'=> 2])->value('openid');
                        $wx->sendTemplate([
                            'openid'=> $openid,
                            'template_id'=> 'VkOPusrnpM5ueEl1WCcS9Pf7CBghPYMmWtkSrsCn9Ao',
                            'page'=> 'pages/repair/worker/order/order',
                            'data'=>[
                                "first"=> [
                                    "value"=> $v['details'],
                                ],
                                "keyword1"=> [
                                    "value"=> $v['order_no'],
                                ],
                                "keyword2"=> [
                                    "value"=> $v['add_time'],
                                ],
                            ]
                        ]);

                        db('repair_order')->where(['id'=> $v['id']])->update(['is_tui'=> 1]);
                    }
                }
            }
        }

    }

    // 师傅订单结算

    function money()
    {
        $data = db('accept_order a')
            ->join('repair_order o', 'o.id = a.o_id')
            ->join('customer c', 'a.customer_id = c.id')
            ->where(['a.status'=> 40, 'is_solve'=> 0, 'o.status'=> 40])
            ->field('o.customer_id as id, a.earnest_money, a.commission, c.unionid, a.id as a_id, o.type, a.customer_id')
            ->select();

        $wx = new Wx();

        foreach ($data as $v)
        {
            $value = ServiceConfig::where(['id'=> $v['type']])->value('tiger_tee');

            $openid = db('customer')->where(['unionid'=> $v['unionid'], 'type'=> 2])->value('openid');
            $wx->sendTemplate([
                'openid'=> $openid,
                'template_id'=> 'KO7PzleBytwcD9tQ5bGixBdI7ewiSXIf_lM9az1JFWc',
                'page'=> 'pages/mine/mine',
                'data'=>[
                    "first"=> [
                        "value"=> "您有收益到账了！！！",
                    ],
                    "keyword1"=> [
                        "value"=> "恭喜您获得{$v['earnest_money']}元现金和{$value}虎牙！！！",
                    ],
                    "keyword2"=> [
                        "value"=> date('Y-m-d H:i:s'),
                    ],
                ]
            ]);

            db('customer')->where(['id'=> $v['customer_id']])->setInc('money', $v['earnest_money']);
            db('customer')->where(['id'=> $v['customer_id']])->setInc('tiger_tee', $value);

            $parent_id = db('master_log')->where(['u_id'=> $v['id']])->value('parent_id');
            if($parent_id)
            {
                $unionid =  db('customer')->where(['id'=> $parent_id])->value('unionid');
                $openid = db('customer')->where(['unionid'=> $unionid, 'type'=> 2])->value('openid');
                $wx->sendTemplate([
                    'openid'=> $openid,
                    'template_id'=> 'KO7PzleBytwcD9tQ5bGixBdI7ewiSXIf_lM9az1JFWc',
                    'page'=> 'pages/mine/mine',
                    'data'=>[
                        "first"=> [
                            "value"=> "您有收益到账了！！！",
                        ],
                        "keyword1"=> [
                            "value"=> "恭喜您获得{$v['commission']}元现金和{$value}虎牙！！！",
                        ],
                        "keyword2"=> [
                            "value"=> date('Y-m-d H:i:s'),
                        ],
                    ]
                ]);

                db('customer')->where(['id'=> $parent_id])->setInc('money', $v['commission']);
                db('customer')->where(['id'=> $parent_id])->setInc('tiger_tee', $value);
            }

            db('accept_order')->where(['id'=> $v['a_id']])->update(['is_solve'=> 1]);
        }
    }

    // 确认订单

    function submit()
    {
        $time = date('Y-m-d H:i:s', time() - 172800);
        $list = db('accept_order a')
            ->join('repair_order o', 'o.id = a.o_id')
            ->where(['a.status'=> 40, 'o.status'=> 36, 'a.add_time'=> ['<', $time]])
            ->field('o.type, a.o_id, o.customer_id')
            ->select();

        foreach ($list as $v)
        {
            db('repair_order')->where(['id'=> $v['o_id']])->update(['status'=> 40]);
            $value = ServiceConfig::where(['id'=> $v['type']])->value('tiger_tee');
            Customer::where(['id'=> $v['customer_id']])->setInc('tiger_tee', $value);
        }
    }

    // 开奖
    function open()
    {
        $where = [
            'status'=> 1
        ];
        $data = db('award')->where($where)->field('company_id, award_id, reward_id, create_time, type, condition')->select();
        foreach ($data as $v)
        {
            if($v['type'] == 1)
            {
                if(strtotime($v['create_time']) + 86400 * $v['condition'] > time())
                {
                    continue;
                }
            }elseif ($v['type'] == 2) {
                if(strtotime($v['create_time']) > time())
                {
                    continue;
                }
            }
            Db::startTrans();
            try
            {

                $prize = db('reward')->where(['reward_id'=> ['in', $v['reward_id']]])->field('name, reward_id, value, num')->order('num')->select();
                foreach ($prize as $kk=> $vv)
                {
                    $ids = db('lottery')->where([
                        'is_prize'=> 0,
                        'award_id'=> $v['award_id']
                    ])->orderRaw('rand()')->limit($vv['num'])->field('lottery_id, customer_id')->select();
//                    dump($ids);
                    db('lottery')->where(['lottery_id'=> ['in', array_column($ids, 'lottery_id')]])->update([
                        'level'=> $kk + 1,
                        'reward_id'=> $vv['reward_id'],
                        'reward_name'=> $vv['name'],
                        'is_prize'=> 1
                    ]);

//                    echo 123121;
                    $insert = [];
                    foreach ($ids as $var)
                    {
                        $data2 = db('coupon')->where(['coupon_id'=> $vv['value']])->field('name, expired_type, start_time, expired_date, uid')->find();
                        if($data2['expired_type'] == 1)
                        {
                            $post['start_time'] = $data2['start_time'];
                        }else{
                            $post['start_time'] = date('Y-m-d');
                        }
                        $post['end_time'] = date('Y-m-d', strtotime($post['start_time']) + $data2['expired_date'] * 86400);
                        $post['uid'] = $data2['uid'];
                        $post['coupon_id'] = $vv['value'];
                        $post['customer_id'] = $var['customer_id'];
                        $post['lottery_id'] = $var['lottery_id'];
                        $insert[] = $post;
                    }
                    db('my_coupon')->insertAll($insert);

                }

                db('award')->where(['award_id'=> $v['award_id']])->update([
                    'status'=> 2,
                    'open_time'=> date('Y-m-d H:i:s')
                ]);
                Db::commit();
            }catch (Exception $exception) {
                Db::rollback();
                echo $exception->getMessage();
            }
        }
    }

}